package com.servlet;

import com.util.FileDownLoad;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/imagedownload")
public class ImageDownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        File file = new File("F:\\kaifamiao.1\\JavaWeb\\temp\\upload");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        File[] files = file.listFiles(File::isFile);
        if (files != null && files.length > 0) {
            StringBuilder html = new StringBuilder("<style>table, tr,td{border:1px solid black;}</style> <h1>图片下载目录</h1>");
            html.append("<table>" + "<tr>" + "<td>序号</td>" + "<td>文件名</td>" + "<td>文件大小</td>" + "<td>修改时间</td>" + "<td>下载</td>" + "</tr>");
            for (int i = 0; i < files.length; i++) {

                String downloadLink = "/Servlet10_16/download?file=" + files[i].getName();
                html.append("<tr>" + "<td>")
                        .append(i + 1).append("</td>")
                        .append("<td>").append(files[i].getName()).append("</td>")
                        .append("<td>").append(FileDownLoad.getSize(files[i].length())).append("KB").append("</td>")
                        .append("<td>").append(FileDownLoad.getData(files[i].lastModified())).append("</td>")
                        .append("<td><a").append(" href=").append(downloadLink).append(">下载文件</a>").append("</td>").append("</tr>");
            }
            html.append("</table>");
            resp.getWriter().write(html.toString());
        }else {
            resp.getWriter().write("<h3>服务端上传目录为空</h3>");
        }
    }
}
